<template>
	<view class="" style="position: relative;padding-top: 10vh;background: #202020;">
		<image src="/static/WechatIMG25.jpg" mode="scaleToFill"
			style="width: 100vw;height: 90vh;position: absolute;z-index: 1;"></image>
		<view class="box"
			style="position: relative;z-index: 100;width: 531rpx;height: 531rpx;padding-top: 18.41%;margin: 0 auto;">
			<div style="position: relative;">
				<!-- 修改所有旋转元素的类绑定 -->
				<image class="image-first" :style="{animationPlayState: btn_loading ? 'running' : 'paused'}"
					style="position: absolute;width: 448rpx;height: 448rpx;" src="/static/2.png" mode="aspectFit">
				</image>
				
				<image class="image-second" :style="{animationPlayState: btn_loading ? 'running' : 'paused'}"
					style="position: absolute;width: 312rpx;height: 312rpx;" src="/static/3.png" mode="aspectFit">
				</image>
				
				<image class="image-fourthly" :style="{animationPlayState: btn_loading ? 'running' : 'paused'}"
					style="position: absolute;width: 531rpx;height: 531rpx;"
					src="/static/1.png" mode="aspectFit"></image>
				
				<image v-if="btn_loading||isShow" class="image-second" :style="{animationPlayState: btn_loading ? 'running' : 'paused'}"
					style="position: absolute;width: 312rpx;height: 312rpx;" src="/static/4.png" mode="aspectFit">
				</image>
				
				<image :class="btn_loading? 'image-thirdly' :'image-thirdly-first'"
						style="position: absolute;width: 50rpx;height: 74rpx;" src="/static/5.png" mode="aspectFit"></image>
				</div>
		</view>
		<view v-if="!bleDevs.length" class="" @click="btn_click"
			style="position: absolute;top: 100.63%;z-index: 1000;transform: translate(-50%,50%);left: 50%;display: flex;">
			<image src="/static/left.png" mode="aspectFit" style="width: 21rpx;
height: 63rpx;"></image>
			<text class="custom-font-text">{{ !btn_loading ? '搜索设备':'设备搜索中...'}}</text>
			<image class="right" src="/static/left.png" mode="aspectFit" style="width: 21rpx;
height: 63rpx;"></image>
		</view>
		<view v-else class="" style="position: relative;z-index: 1000;padding-top: 40rpx;">
			<scroll-view scroll-y class="box" style="max-height: 500rpx;">
				<view style="display: flex;flex-direction: column;align-items: center;">
					<view class="" v-for="(item,index) in bleDevs" :key="index" style="display: flex;margin-bottom: 9rpx;">
						<image src="/static/left.png" mode="aspectFit" style="width: 21rpx;
height: 63rpx;"></image>
						<view class="custom-font-text custom-font-text-first">
							<text style="color: #fff;">{{ item.localName||item.name  }}</text>
							<text @click="navtoindex(item)">连接</text>
						</view>
						<image class="right" src="/static/left.png" mode="aspectFit" style="width: 21rpx;
height: 63rpx;"></image>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fontLoaded:false,
				btn_loading: false,
				// 蓝牙列表
				bleDevs: [],
				// 被选中的蓝牙信息服务对象
				choice_item: {},
				deviceId: "",
				serviceId: "",
				isShow:false,
				characteristicId_write: "",
				characteristicId_notify: "",
				inputText: '',
				canvasContext: null,
				// 是否点击item后连接中
				isconnecting: false
			}
		},
		onLoad() {

		},
		onShow: function() {
		},
		onReady() {

		},
		methods: {
			btn_click() {
				if (this.btn_loading) {
					console.log("正在连接，防止重复点击！")
					return
				}
				this.bleDevs = []
				this.btn_loading = true
				this.isShow = true
				this.initBle()
			},
			// 蓝牙点击事件
			navtoindex(item) {
				console.log(item,'item')
				// uni.navigateTo({
				// 	url: '/pages/index/index?item=' + JSON.stringify(item)
				// });
				// return
				let that = this
				console.log(item)
				that.choice_item.info = item
				if (that.isconnecting) {
					console.log("请勿重复点击")
					return
				}

				that.isconnecting = true
				that.deviceId = item.deviceId
				console.log(item.deviceId)
				setTimeout(() => {
					that.createBLEConnection(item.deviceId)
				}, 100)
			},
			initBle() {
				uni.closeBluetoothAdapter({
					success(res) {
						console.log(res)
						console.log("关闭蓝牙适配器")
					}
				})
				let that = this
				console.log('--------------------初始化ble----------------');
				that.bleDevs = [];
				// setTimeout(() => {
				// 	that.bleDevs = [
				// 		{localName:'数据3213213',id:1},
				// 		{localName:'数据321321',id:2},
				// 		{localName:'数据312312',id:3},
				// 	]
				// 	this.btn_loading = false
				// }, 300)
				// return
				uni.openBluetoothAdapter({
					success: (res) => { //已打开
						uni.getBluetoothAdapterState({ //蓝牙的匹配状态
							success: (row) => {
								console.log(row)
								// 开始搜索蓝牙设备
								setTimeout(() => {
									that.startBluetoothDeviceDiscovery()
								}, 300)
							},
							fail(error) {
								uni.showToast({
									icon: 'none',
									title: '查看手机蓝牙是否打开'
								});
								that.btn_loading = false
								
							}
						});
					},
					fail: err => { //未打开
						uni.showToast({
							icon: 'none',
							title: '查看手机蓝牙是否打开'
						});
						that.btn_loading = false
					}
				})
			},
			// 开始搜索蓝牙设备
			startBluetoothDeviceDiscovery() {
				let _this = this
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						console.log('搜索蓝牙外围设备完成', res)
						_this.timer1 = setTimeout(() => { //加个延迟、目的是为了设备搜索完毕再获取列表，不然获取为空列表
							// 获取设备列表
							_this.onBluetoothDeviceFound()
						}, 1000)
					},
					fail: (err) => {
						console.log(err)
						// uni.showToast({
						// 	icon: 'none',
						// 	title: '搜索失败，请开启蓝牙和定位权限后重试'
						// });
						_this.btn_loading = false
					}
				})
			},
			// 获取设备列表
			onBluetoothDeviceFound() {
				let that = this
				uni.getBluetoothDevices({
					success: function(res) {
						console.log(res.devices,'res.devices')
						//过滤掉name为空的设备
						var bluetoothArr = res.devices.filter(function(obj) {
							return (
									(obj.name && obj.name.startsWith("科虎") || obj.localName &&
										obj.localName.startsWith("科虎"))
								) &&
								obj.RSSI !== 0
						})
						that.bleDevs = bluetoothArr
						console.log("设备列表有" + that.bleDevs)
						that.bleDevs.forEach(u => {
							console.log(u.localName, u.name)
							if (u.name.includes("科虎")) {
								u.name = u.name.replace("科虎", "飞利浦")
							}
							if (u.localName.includes("科虎")) {
								u.localName = u.localName.replace("科虎", "飞利浦")
							}
						})
					},
					fail: function() {
						console.log("搜索蓝牙设备失败");
						uni.showToast({
							title: '搜索蓝牙设备失败或附近暂无开启的蓝牙设备',
							icon: 'none',
							duration: 2000
						})
						that.btn_loading = false
					},
					complete: function() {
						console.log('搜索完成')
						//设备获取完成之后  停止搜索
						uni.stopBluetoothDevicesDiscovery({
							success(res) {
								console.log('停止搜索蓝牙', res)
								that.btn_loading = false
							}
						})
					}
				})
			},
			//选择设备连接把deviceId传进来
			createBLEConnection(deviceId) {
				let that = this
				// this.deviceId = deviceId
				// this.pageLoading = true
				//连接蓝牙
				console.log("#####连接蓝牙")
				uni.showLoading({
					title: '连接中'
				});
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: deviceId,
					timeout: 2000,
					success(res) {
						console.log("蓝牙连接成功", res)
						console.log("device id :" + that.deviceId)
						uni.hideLoading();

						setTimeout(() => {

							// 设置最大传输字节  这里根据情况自己设置

							uni.setBLEMTU({
								deviceId: deviceId,
								mtu: 240, //传输字节数
								success() {
									console.log("设置成功")
									// 获取已连接设备列表
									// that.getConnectedBluetoothDevices()

									// that.pageLoading = false
									//获取服务
									// that.getBLEDeviceServices(this.deviceId)
								},
								fail() {
									// console.log("设置mtu失败");
								},
								complete() {
									console.log("complate")
								}
							})
							//获取服务
							that.getBLEDeviceServices(deviceId)

						}, 1000)
					},
					fail(res) {
						uni.hideLoading();
						if (res.errno === 1509007) {
							console.log("已经连接");
							uni.navigateTo({
								url: '/pages/index/index?item=' + JSON.stringify(that.choice_item)
							});
						} else {
							console.log("蓝牙连接失败", res)
							uni.showToast({
								icon: 'none',
								title: '蓝牙连接失败,请重试'
							})
							uni.closeBLEConnection({
								deviceId,
								success(res) {
									console.log(res)
								}
							})
						}
					},
					complete() {
						uni.hideLoading();
						that.isconnecting = false
					}
				})
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices(deviceId) {
				let that = this
				uni.getBLEDeviceServices({
					deviceId: deviceId,
					success: (res) => {
						console.log("获取服务成功", res)
						//这里会获取到好多个services  uuid  根据实际情况选择自己需要的服务
						// console.log("services", res.services)
						if (res.services.length > 0) {
							console.log("services:" + res.services)
							try {
								for (var i = 0; i < res.services.length; i++) {
									console.log(res.services[i])
								}
								let serviceId = res.services[1].uuid //根据我们的设备  使用的是第三个服务
								that.serviceId = res.services[1].uuid
								// //获取服务特征
								that.getBLEDeviceCharacteristics(deviceId, serviceId)
							} catch (error) {
								console.log(error)
								uni.showToast({
									icon: 'none',
									title: '蓝牙连接服务失败'
								})
								return
							}

						} else {
							uni.hideLoading();
						}

					},
					fail(res) {
						console.log("获取蓝牙服务失败", res)
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '蓝牙连接服务失败'
						})
					},
					complete() {
						that.isconnecting = false
						uni.hideLoading();
					}
				})
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				console.log("------------------进入特征------------------");
				let that = this
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success: (res) => {
						console.log("res.characteristics.", res.characteristics)
						// that.characteristics = res.characteristics
						// 这里哪个特征支持notify或indicate  就选择哪个
						try {

							that.characteristicId_write = res.characteristics[0].uuid // 写数据的特征uuid
							that.characteristicId_notify = res.characteristics[3].uuid //通知
						} catch (error) {
							console.log(error)
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: '获取蓝牙信息失败'
							})
							that.isconnecting = false
							return
						}
						// 爆闪
						// that.send("5A040103")
						// that.notifyBLECharacteristicValueChange(deviceId, serviceId, that.characteristicId2)
						// 进入主界面
						// 组装对象
						// choice_item:{},
						// deviceId: "",
						// serviceId: "",
						// characteristicId: ""
						let service_info = {}
						service_info.deviceId = that.deviceId
						service_info.serviceId = that.serviceId
						service_info.characteristicId_write = that.characteristicId_write
						service_info.characteristicId_notify = that.characteristicId_notify
						// that.choice_item.ideviceId = that.deviceId
						// that.choice_item.serviceId = that.serviceId
						// that.choice_item.characteristicId_write = that.characteristicId_write
						// that.choice_item.characteristicId_notify = that.characteristicId_notify

						that.choice_item.service = service_info


						// 连接成功之后  把已连接的设备从设备列表中删除
						that.deleteConnectedBleInfo()
						uni.hideLoading();
						// 跳转主页
						uni.redirectTo({
							url: '/pages/index/index?item=' + JSON.stringify(that.choice_item)
						});
						// this.notifyBLECharacteristicValueChange(that.deviceId,that.serviceId,that.characteristicId_notify)
					},
					fail: (res) => {
						console.log(res)
						uni.showToast({
							icon: 'none',
							title: '蓝牙信息失败'
						})
					}
				})
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
				console.log("进入notify代码")
				let that = this
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: deviceId,
					serviceId: serviceId,
					characteristicId: characteristicId,
					success: (res) => {
						console.log("notify 监听开始")


						//监听设备发送数据
						uni.onBLECharacteristicValueChange((res) => {
							console.log("监听成功", res.value)
							// ArrayBuffer
							//res.value是ArrayBuffer类型的，转换成需要的格式，我们再进行操作
							//这是转换成ASCII码
							let str = that.arrayBufferToHexString(res.value)
							//转换后的数据
							that.data = str
							console.log("数据变化" + str)
						})
					},
					fail: (res) => {
						console.log('启用 notify 功能失败', res)
						uni.showToast({
							icon: 'none',
							title: '设备暂不支持接收数据',
							duration: 3000
						})
					}
				})
			}
			// buffer转换为16进制字符串
			,
			arrayBufferToHexString(buffer) {
				let hexString = Array.from(new Uint8Array(buffer)).map(byte => ("00" + byte.toString(16)).slice(-2)).join(
					"");
				return hexString;
			},
			// 删除列表连接过的蓝牙信息
			deleteConnectedBleInfo() {
				let that = this
				let index = ''
				that.bleDevs.forEach((i, key) => {
					console.log("遍历设备列表移除");
					if (i.deviceId == that.deviceId) {
						index = key
					}
				})
				if (index !== '') {
					that.bleDevs.splice(index, 1)
				}
			},
			// 写入数据
			send(hexstr) {
				let buffer = this.hexStringToArrayBuffer(hexstr)
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId_write,
					value: buffer,
					success(res) {
						console.log('writeBLECharacteristicValue success', res.errMsg)
						// uni.showToast({
						// 	title: 'write指令发送成功'
						// })
					},
					fail(err) {
						console.error(err)
						uni.showToast({
							title: '档位调节失败,请检查连接',
							icon: 'error'
						})
					}
				})
			},

			// 将十六进制字符串转换为 ArrayBuffer 对象
			hexStringToArrayBuffer(hexString) {
				let bytes = hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16));
				return new Uint8Array(bytes).buffer;
			},
			test_send() {
				this.send('5A040103')
			}
		}
	}
</script>


<style>
	/* ...其他样式保持不变... */
.container {
		padding: 20px;
		font-size: 14px;
		line-height: 24px;
	}

	.custom-font-text {
		width: 340rpx;
		color: #40BFFF;
		font-size: 35rpx;
		/* font-family: 'CustomFont'; */
		height: 63rpx;
		line-height: 63rpx;
		/* margin: 30rpx 0 30rpx 0; */
		text-align: center;
		display: block;

	}

	.custom-font-text-first {
		display: flex;
		margin: 0 10rpx;
		height: 63rpx;
		line-height: 63rpx;
		justify-content: space-between;
	}

	.list-item {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		padding: 10px 0 10px 0;
		box-sizing: border-box;
		border: 1px solid #000;
		border-style: none none solid none;
		border-bottom-color: lightgray;
	}

	.list-item:last-child {
		border-style: none;
	}

	.button {
		position: fixed;
		width: 690rpx;
		bottom: 30rpx;
	}

	.image-first-first {
		top: 40.28rpx;
		left: 40.28rpx;
	}
	/* 修改动画控制方式 */
	.image-first {
		top: 40.28rpx;
		left: 40.28rpx;
		animation: spinJust 1s linear infinite;
		-webkit-animation: spinJust 1s linear infinite;
		animation-play-state: paused; /* 默认暂停 */
	}
	.right {
		transform: rotate(180deg);
	}
	.image-second {
		left: 111.11rpx;
		top: 111.11rpx;
		animation: spinJust 1s linear infinite;
		-webkit-animation: spinJust 1s linear infinite;
		animation-play-state: paused; /* 默认暂停 */
	}

	.image-thirdly-first {
		top: 50%;
		left: 50%;
		transform: translate(-50%, 320%);
	}
	
	.image-thirdly {
		/* animation: spin 2s linear infinite;
		-webkit-animation: spin 2s linear infinite; */
		top: 50%;
		left: 50%;
		transform: translate(-50%, 320%);
	}
	/* .image-fourthly {
		animation: spin 3s linear infinite;
		-webkit-animation: spin 3s linear infinite;
		animation-play-state: paused;
	} */

	/* 定义旋转动画 */
	@keyframes spin {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	}

	@keyframes spinJust {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(-360deg);
		}
	}

	/* 兼容旧版浏览器 */
	@-webkit-keyframes spin {
		from {
			-webkit-transform: rotate(0deg);
		}
		to {
			-webkit-transform: rotate(-360deg);
		}
	}
</style>